package cj.web.marry.controllers;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.Page;
import cj.utils.sms.SendSMSUtil;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.BaseController;
import cj.web.mall.dao.GoodsDAO;
import cj.web.mall.dao.UserDAO;
import cj.web.marriage.constants.MarriageBusinessStateEnum;
import cj.web.marriage.constants.MarriageBusinessTypeEnum;
import cj.web.marriage.constants.RegAddressEnum;
import cj.web.marriage.constants.YYWeddingFeastTypeEnum;
import cj.web.marry.dao.YYBookingDAO;

@Path("yYBooking")
public class YYBookingController extends BaseController{
	
	protected static final Log logger = LogFactory.getLog(VideosController.class); 
	
	@Autowired
	private YYBookingDAO yYBookingDao;
	@Autowired
	private UserDAO userDao;
	@Autowired
	private GoodsDAO goodsDao;
	
	//----------------婚典三期首页
	@Get("homeCode")  //首页商品列表
	public String homeCode(Model model,@Param("code")String code, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,Constants.weixinkey.AppID,Constants.weixinkey.AppSecret);
		setCookie(response, "openId", openId);
//		setCookie(response, "openId", "okInCw1-sAjdtpxRNeddfeWnRqaM");
		return "r:home";
	}
	
	@Get("home")  //首页商品列表
	public String home(Model model, HttpServletRequest request) throws Exception{
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		
		model.add("Title", "长江婚典商城-您的专属婚品");
		model.add("Desc", "只为您专属打造");
		model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/yYBooking/homeCode"+oauth_end);
		//model.add("ImgUrl", "images/banner.png");
		
		//商品
		List<Map> repgoods = goodsDao.goodsList();
		//婚庆商品信息表
		List<Map> repWeddingCelebrations = yYBookingDao.queryWeddingCelebration(0, 2, 99);
		//婚宴商家信息表
		List<Map> repWeddingFeasts = yYBookingDao.queryWeddingFeast(0, 2, "");
		//婚纱照商家信息表
		List<Map> repWeddingPhotos = yYBookingDao.queryWeddingPhoto(0, 2, "");
		//商家预约信息表
		List<Map> repBusinessRess = yYBookingDao.queryYYBusinessRes(0, 2, "");
		
		model.add("repGoods", repgoods.subList(0, 2));
		model.add("repCelebrations", repWeddingCelebrations);
		model.add("repFeasts", repWeddingFeasts);
		model.add("repPhotos", repWeddingPhotos);
		model.add("repBusinessRess", repBusinessRess);
		
		return "/views/marry/booking/index.vm";
	}
	
	@Post("list")  //首页商品列表方法
	public String list(){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		//商品
		List<Map> repgoods = goodsDao.goodsList().subList(0, 1);
		//婚庆商品信息表
		List<Map> repWeddingCelebrations = yYBookingDao.queryWeddingCelebration(0, 1, 99);
		//婚宴商家信息表
		List<Map> repWeddingFeasts = yYBookingDao.queryWeddingFeast(0, 1, "");
		//婚纱照商家信息表
		List<Map> repWeddingPhotos = yYBookingDao.queryWeddingPhoto(0, 1, "");
		//商家预约信息表
		List<Map> repBusinessRess = yYBookingDao.queryYYBusinessRes(0, 1, "");
		
		jo.put("repGoods", repgoods);
		jo.put("repCelebrations", repWeddingCelebrations);
		jo.put("repFeasts", repWeddingFeasts);
		jo.put("repPhotos", repWeddingPhotos);
		jo.put("repBusinessRess", repBusinessRess);
		
		return "@" + jo.toString();
	}
	
	//----------------婚庆商品信息
	
	/**
	 * 查询婚庆
	 * @param model
	 * @return
	 */
	@Get("showCelebration")
	public String showCelebration(Model model){
		model.add("YYWeddingFeastTypeEnum",EnumSet.allOf(YYWeddingFeastTypeEnum.class));
		return "/views/marry/booking/celebrationList.vm";
	}
	
	/**
	 * 婚庆分页
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@Get("celebrationlis/{start:[0-9]+}/length/{length:[0-9]+}/type/{type:[0-9]+}")
	public String celebrationlis(@Param("start") int start,@Param("length") int length,
			@Param("type") int type, HttpServletRequest request) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> repsList = yYBookingDao.queryWeddingCelebration(start*length,length,type);
		
		for(Map rep:repsList){
			rep.put("typeName", YYWeddingFeastTypeEnum.getName(Integer.parseInt(rep.get("type").toString())));
		}
		
		int totalCount = yYBookingDao.queryWeddingCelebrationsize(type);
		//分页计算
		Page p= new Page<Map>(0, length, repsList, totalCount);
		jo.put("list", repsList);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		
		return "@"+jo.toString();
	}
	
	/**
	 * 婚庆详情
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("detailCelebration/{id:[0-9]+}")
	public String detailCelebration(Model model,@Param("id") int id){
		
		List<Map> rep = yYBookingDao.queryWeddingCelebrationById(id);
		if(rep != null && rep.size()>0){
			model.add("obj", rep.get(0));
			model.add("typeName", YYWeddingFeastTypeEnum.getName(Integer.parseInt(rep.get(0).get("type").toString())));
			return "/views/marry/booking/celebrationDetail.vm";
		}else{
			model.add("warning", "该信息已下架");
			return "/views/marry/booking/nothing.vm";
		}
	}
	
	//----------------婚宴商家信息
	
	/**
	 * 查询婚宴
	 * @param model
	 * @return
	 */
	@Get("showFeast")
	public String showFeast(Model model){
		model.add("AddressEnum", EnumSet.allOf(RegAddressEnum.class));
		return "/views/marry/booking/feastList.vm";
	}
	
	/**
	 * 婚宴分页
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@Get("feastlis/{start:[0-9]+}/length/{length:[0-9]+}/area/{areaId:[0-9]+}")
	public String feastlis(@Param("start") int start,@Param("length") int length,
			@Param("areaId") int areaId, HttpServletRequest request) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String area = "";
		if(areaId!=0){
			area = RegAddressEnum.getNameOnly(areaId);//婚宴区域信息
		}
		
		List<Map> repsList = yYBookingDao.queryWeddingFeast(start*length,length,area);
		int totalCount = yYBookingDao.queryWeddingFeastsize(area);
		//分页计算
		Page p= new Page<Map>(0, length, repsList, totalCount);
		jo.put("list", repsList);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		
		return "@"+jo.toString();
	}
	
	/**
	 * 婚宴详情
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("detailFeast/{id:[0-9]+}")
	public String detailFeast(Model model,@Param("id") int id){
		
		List<Map> rep = yYBookingDao.queryWeddingFeastById(id);
		if(rep != null && rep.size()>0){
			model.add("obj", rep.get(0));
			return "/views/marry/booking/feastDetail.vm";
		}else{
			model.add("warning", "该信息已下架");
			return "/views/marry/booking/nothing.vm";
		}
	}
	
	//----------------婚纱照商家信息
	
	/**
	 * 查询婚纱照
	 * @param model
	 * @return
	 */
	@Get("showPhoto")
	public String showPhoto(Model model){
		model.add("AddressEnum", EnumSet.allOf(RegAddressEnum.class));
		return "/views/marry/booking/photoList.vm";
	}
	
	/**
	 * 婚纱照分页
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@Get("photolis/{start:[0-9]+}/length/{length:[0-9]+}/area/{areaId:[0-9]+}")
	public String photolis(@Param("start") int start,@Param("length") int length,
			@Param("areaId") int areaId,HttpServletRequest request) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String area = "";
		if(areaId!=0){
			area = RegAddressEnum.getNameOnly(areaId);//婚纱照区域信息
		}
		
		List<Map> repsList = yYBookingDao.queryWeddingPhoto(start*length,length,area);
		int totalCount = yYBookingDao.queryWeddingPhotosize(area);
		//分页计算
		Page p= new Page<Map>(0, length, repsList, totalCount);
		jo.put("list", repsList);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		
		return "@"+jo.toString();
	}
	
	/**
	 * 婚纱照详情
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("detailPhoto/{id:[0-9]+}")
	public String detailPhoto(Model model,@Param("id") int id){
		
		List<Map> rep = yYBookingDao.queryWeddingPhotoById(id);
		
		if(rep != null && rep.size()>0){
			model.add("obj", rep.get(0));
			return "/views/marry/booking/photoDetail.vm";
		}else{
			model.add("warning", "该信息已下架");
			return "/views/marry/booking/nothing.vm";
		}
		
	}
	
	//----------------商家预约信息
	
	/**
	 * 查询商家信息
	 * @param model
	 * @return
	 */
	@Get("showBusinessRess")
	public String showBusinessRess(Model model){
		model.add("AddressEnum", EnumSet.allOf(RegAddressEnum.class));
		return "/views/marry/booking/businessRessList.vm";
	}
	
	/**
	 * 商家信息分页
	 * @param start
	 * @param length
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@Get("businessResslis/{start:[0-9]+}/length/{length:[0-9]+}/area/{areaId:[0-9]+}")
	public String businessResslis(@Param("start") int start,@Param("length") int length,
			@Param("areaId") int areaId,HttpServletRequest request) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String area = "";
		if(areaId!=0){
			area = RegAddressEnum.getNameOnly(areaId);//区域信息
		}
		
		List<Map> repsList = yYBookingDao.queryYYBusinessRes(start*length,length,area);
		int totalCount = yYBookingDao.queryYYBusinessRessize(area);
		//分页计算
		Page p= new Page<Map>(0, length, repsList, totalCount);
		jo.put("list", repsList);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		
		return "@"+jo.toString();
	}
	
	/**
	 * 商家信息详情
	 * @param model
	 * @param id
	 * @return
	 */
	@Get("detailBusinessRes/{id:[0-9]+}")
	public String detailBusinessRes(Model model,@Param("id") int id){
		
		List<Map> rep = yYBookingDao.queryYYBusinessResById(id);
		
		if(rep != null && rep.size()>0){
			model.add("obj", rep.get(0));
			return "/views/marry/booking/businessRessDetail.vm";
		}else{
			model.add("warning", "该信息已下架");
			return "/views/marry/booking/nothing.vm";
		}
		
	}
	
	//----------------预约信息
	
	/**
	 * 预约界面
	 * @param model
	 * @param businessId
	 * @param businessType
	 * @return
	 */
	@Get("showBooking/{businessId:[0-9]+}/type/{businessType:[0-9]+}")
	public String showBooking(Model model,@Param("businessId") int businessId,@Param("businessType") int businessType){
		
		List<Map> rep = new ArrayList<Map>();
		if(businessType==MarriageBusinessTypeEnum.HSZYY.getValue()){
			rep = yYBookingDao.queryWeddingPhotoById(businessId);
		}else if(businessType==MarriageBusinessTypeEnum.HQYY.getValue()){
			rep = yYBookingDao.queryWeddingCelebrationById(businessId);
		}else if(businessType==MarriageBusinessTypeEnum.HYYD.getValue()){
			rep = yYBookingDao.queryWeddingFeastById(businessId);
		}else if(businessType==MarriageBusinessTypeEnum.SJYD.getValue()){
			rep = yYBookingDao.queryYYBusinessResById(businessId);
		}
		
		if(rep != null){
			model.add("businessObj", rep.get(0));
			model.add("businessType", businessType);
			model.add("businessId", businessId);
			model.add("currentDate", DateUtils.getNowTime(DateUtils.DATE_SMALL_STR));
			return "/views/marry/booking/bookingForm.vm";
		}else{
			model.add("warning", "该信息已下架");
			return "/views/marry/booking/nothing.vm";
		}
	}
	
	/**
	 * 保存预约信息
	 * @param businessId	业务ID
	 * @param businessType	业务类型
	 * @param name			联系人名称
	 * @param phone			联系人电话
	 * @param bookingAt		预约时间
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@Post("saveBooking")
	public String saveBooking(@Param("businessId") int businessId,@Param("businessType") int businessType,
			@Param("name") String name,@Param("phone") String phone,@Param("bookingAt") String bookingAt,
			HttpServletRequest request) throws ParseException {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			if( isLogin(request) ){
				
				String l_phone = getCookieValueByName(request, "phone");
				int buyerId = userDao.getBuyerId(l_phone);
				
				List<Map> rep = new ArrayList<Map>();
				if(businessType==MarriageBusinessTypeEnum.HSZYY.getValue()){
					rep = yYBookingDao.queryWeddingPhotoById(businessId);
				}else if(businessType==MarriageBusinessTypeEnum.HQYY.getValue()){
					rep = yYBookingDao.queryWeddingCelebrationById(businessId);
				}else if(businessType==MarriageBusinessTypeEnum.HYYD.getValue()){
					rep = yYBookingDao.queryWeddingFeastById(businessId);
				}else if(businessType==MarriageBusinessTypeEnum.SJYD.getValue()){
					rep = yYBookingDao.queryYYBusinessResById(businessId);
				}
				
				if(rep != null && rep.size()>0){
					int id = yYBookingDao.create(buyerId, businessId, businessType, name, phone, bookingAt, 
							MarriageBusinessStateEnum.WCL.getValue(), l_phone, l_phone);
					jo.put("id", id);
					
					//发送短信通知
					String tempid = "236323";
					SendSMSUtil.sendSMS(accountSid, accountToken, appId, phone, tempid, null);
					
					return "@" + jo.toString();
				}else{
					jo.put("rtnMsg", "该信息已下架");
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					return "@" + jo.toString();
				}
				
			}else{
				jo.put("returnPage", "yYBooking/showBooking/" + businessId + "/type/" + businessType);
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				return "@" + jo.toString();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jo.put("returnPage", "yYBooking/showBooking/" + businessId + "/type/" + businessType);
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			return "@" + jo.toString();
		}
		
	}
	
	/**
	 * 空
	 * @param model
	 * @param warning
	 * @return
	 */
	@Get("nothing")
	public String nothing(Model model,@Param("warning") String warning){
		model.add("warning", warning);
		return "/views/marry/booking/nothing.vm";
	}
	
	//----------------我的预约信息
	
	/**
	 * 我的预约信息列表
	 * @param model
	 * @return
	 */
	@Get("showMyBooking")
	public String showMyBooking(Model model, HttpServletRequest request){
		
		int start=0;
		int length=999999;
		//是否登录
		if( isLogin(request) ){
			
			String l_phone = getCookieValueByName(request, "phone");
			int buyerId = userDao.getBuyerId(l_phone);
			
			List<Map> repsList = yYBookingDao.queryBooking(start*length,length,buyerId);
			for(Map rep:repsList){
				List<Map> repObjs = new ArrayList<Map>();
				//预约类型
				int businessType = Integer.parseInt(rep.get("businessType").toString());
				//预约ID
				int businessId = Integer.parseInt(rep.get("businessId").toString());
				if(businessType==MarriageBusinessTypeEnum.HSZYY.getValue()){
					repObjs = yYBookingDao.queryWeddingPhotoById(businessId);
				}else if(businessType==MarriageBusinessTypeEnum.HQYY.getValue()){
					repObjs = yYBookingDao.queryWeddingCelebrationById(businessId);
				}else if(businessType==MarriageBusinessTypeEnum.HYYD.getValue()){
					repObjs = yYBookingDao.queryWeddingFeastById(businessId);
				}else if(businessType==MarriageBusinessTypeEnum.SJYD.getValue()){
					repObjs = yYBookingDao.queryYYBusinessResById(businessId);
				}
				
				rep.put("sellerName", repObjs.get(0).get("sellerName").toString());
				rep.put("img", repObjs.get(0).get("img").toString());
			}
			model.add("list", repsList);
		}else{
			return "r:../user/login?returnPage=yYBooking/showMyBooking";
		}
		return "/views/marry/booking/myBookingList.vm";
	}
	
	/**
	 * 预约详情
	 * @param model
	 * @param id
	 * @return
	 * @throws ParseException 
	 */
	@Get("detailMyBooking/{id:[0-9]+}")
	public String detailMyBooking(Model model,@Param("id") int id) throws ParseException{
		List<Map> reps = yYBookingDao.queryBookingById(id);
		
		if(reps != null && reps.size()>0){
			
			Map obj = new HashMap();
			int businessType = Integer.parseInt(reps.get(0).get("businessType").toString());
			int businessId = Integer.parseInt(reps.get(0).get("businessId").toString());
			
			if(businessType==MarriageBusinessTypeEnum.HSZYY.getValue()){
				obj = yYBookingDao.queryWeddingPhotoById(businessId).get(0);
			}else if(businessType==MarriageBusinessTypeEnum.HQYY.getValue()){
				obj = yYBookingDao.queryWeddingCelebrationById(businessId).get(0);
			}else if(businessType==MarriageBusinessTypeEnum.HYYD.getValue()){
				obj = yYBookingDao.queryWeddingFeastById(businessId).get(0);
			}else if(businessType==MarriageBusinessTypeEnum.SJYD.getValue()){
				obj = yYBookingDao.queryYYBusinessResById(businessId).get(0);
			}
			
			model.add("obj", obj);
			model.add("bookingObj", reps.get(0));
			model.add("bookingAt",DateUtils.formatDateStr(reps.get(0).get("bookingAt").toString(),DateUtils.DATE_SMALL_STR));
			return "/views/marry/booking/bookingOrderDetail.vm";
		}else{
			model.add("warning", "该信息已下架");
			return "/views/marry/booking/nothing.vm";
		}
	}
}